package com.hoongs.v1.controller;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.hoongs.v1.dto.UserPageDto;
import com.hoongs.v1.entity.User;
import com.hoongs.v1.entity.WxAuth;
import com.hoongs.v1.service.UserService;
import com.hoongs.v1.utils.Result;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@RestController
@RequestMapping("/user")
@Validated
public class UserController {

    @Resource
    private UserService userService;

    @PostMapping("/login")
    public Result login(String username, String password, String code) {
        return userService.login(username, password, code);
    }

    @PostMapping("/getSessionId")
    public Result getSessionId(String code) {
        return userService.getSessionId(code);
    }

    @PostMapping("/authLogin")
    public Result authLogin(WxAuth wxAuth) {
        return userService.authLogin(wxAuth);
    }

    @GetMapping("/logout")
    public Result logout() {
        return userService.logout();
    }

    @GetMapping("/getAuthStatus")
    public Result getAuthStatus(@RequestHeader("token") String token) {
        return userService.getAuthStatus(token);
    }

    @PostMapping("/setAuthStatus")
    public Result setAuthStatus(String isAuth, @RequestHeader("token") String token) {
        return userService.setAuthStatus(isAuth, token);
    }

    @PostMapping("/save")
    @PreAuthorize("hasAnyAuthority('admin')")
    public Result save(User user) {
        return userService.save(user);
    }

    @PostMapping("/add")
    @PreAuthorize("hasAnyAuthority('admin')")
    public Result add(@Validated User user, BindingResult bindingResult) {
        String res = Result.resultMsg(bindingResult);
        return StringUtils.isNotBlank(res) ? Result.opError(res) : userService.add(user);
    }

    @PostMapping("/remove")
    @PreAuthorize("hasAnyAuthority('admin')")
    public Result remove(String id) {
        return userService.remove(id);
    }

    @PostMapping("/update")
    @PreAuthorize("hasAnyAuthority('admin')")
    public Result update(User user) {
        return userService.update(user);
    }

    @GetMapping("/selectById")
    @PreAuthorize("hasAnyAuthority('admin')")
    public Result selectById(String id) {
        return userService.selectById(id);
    }

    @GetMapping("/selectList")
    @PreAuthorize("hasAnyAuthority('admin')")
    public Result selectList(String name) {
        return userService.selectList(name);
    }

    @GetMapping("/selectPageList")
    @PreAuthorize("hasAnyAuthority('admin')")
    public Result selectPageList(UserPageDto userDto) {
        return userService.selectPageList(userDto);
    }

}
